package http

import (
	"gitee.com/sdynasty/clever/log"
	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus"
	"time"
)

// ServerOption is an HTTP server option.
type ServerOption func(*Server)
type GinEngineHandle func(engine *gin.Engine)

// WithAddress with server address.
func WithAddress(addr string) ServerOption {
	return func(s *Server) {
		s.address = addr
	}
}

// WithTimeout with server timeout.
func WithTimeout(timeout time.Duration) ServerOption {
	return func(s *Server) {
		s.timeout = timeout
	}
}

// WithLogger with server logger.
func WithLogger(logger log.Logger) ServerOption {
	return func(s *Server) {
		s.log = log.NewHelper(log.With(logger, "module", "transport/http"))
	}
}

// WithEngine with server engine.
func WithEngine(engine *gin.Engine) ServerOption {
	return func(s *Server) {
		s.engine = engine
	}
}

// EnableCrossDomain enable CrossDomain.
func EnableCrossDomain() ServerOption {
	return func(s *Server) {
		s.enableCrossDomain = true
	}
}

// EnablePrometheus enable Prometheus.
func EnablePrometheus() ServerOption {
	return func(s *Server) {
		s.enablePrometheus = true
	}
}

// WithLimiter with limiter.
func WithLimiter(limit time.Duration, burst int) ServerOption {
	return func(s *Server) {
		s.enableLimit = true
		s.limiterLimit = limit
		s.limiterBurst = burst
	}
}

const (
	namespace = "mk"
)
func WithPromCounter(subsystem string) ServerOption {
	return func(s *Server) {
		s.promRequests = prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: namespace,
				Subsystem: subsystem,
				Name:      "requests_total",
				Help:      "request(s) total",
			},
			[]string{"method", "path"},
		)
		prometheus.MustRegister(s.promRequests)
	}
}
func WithPromHistogram(subsystem string) ServerOption {
	return func(s *Server) {
		s.promSeconds = prometheus.NewHistogramVec(
			prometheus.HistogramOpts{
				Namespace: namespace,
				Subsystem: subsystem,
				Name:      "requests_cost",
				Help:      "request(s) cost seconds",
			},
			[]string{"method", "path", "http_code", "business_code"},
		)
		prometheus.MustRegister(s.promSeconds)
	}
}